package com.mlkj.serve.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.sd4324530.fastweixin.util.JSONUtil;
import com.github.sd4324530.fastweixin.util.NetWorkCenter;
import com.mlkj.serve.model.User;
import com.mlkj.serve.util.SystemContent;

/**
 * @author hanchen
 *
 */
@Controller
@RequestMapping(value="/oauth")
public class OAuthController {
	
	private static final Logger log = LoggerFactory.getLogger(OAuthController.class);
	/**
	 * 给用户提供登陆入口  也就是引导用户进入授权页面同意授权，获取code
	 * @return
	 */
	@RequestMapping(value="/user")
	public String userLogin(){
		return "login";
	}
	
	/**
	 * 用户同意授权后会重定向到该URL 参数为code=CODE&state=STATE
	 * 若用户禁止授权，则重定向后不会带上code参数，仅会带上state参数redirect_uri?state=STATE
	 * @param code
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value="/code")
	public String getCode(String code,ModelMap modelMap){
		
		String message = "";
		String errmsg = "";
		String accessToken = "";//用户的access_token
		String openId = "" ;//用户的openId
		final Map<String, String> resultMap = new HashMap<String, String>();
		if (code == null || code.equals("")) {
			message ="用户拒绝授权";
			return "showcode";
		}else {
			message = "用户同意授权";
			log.info(message);
			//拼凑请求的URL
			//这里的GET方法很不方便  以后需要优化
			String getUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
			Map<String, String> map = new HashMap<String, String>();
			map.put("appId", SystemContent.APPID);
			map.put("secret",SystemContent.SECRET);
			map.put("code", code);
			map.put("grant_type", "authorization_code");
			NetWorkCenter.get(getUrl, map, new NetWorkCenter.ResponseCallback() {
				
				@Override
				public void onResponse(int resultCode, String resultJson) {
					log.info("由code得到信息："+resultJson);
					resultMap.put("resultJson", resultJson);
				}
			});
		}
		
		if (JSONUtil.getStringFromJSONObject(resultMap.get("resultJson"), "errmsg") == null) {
			log.info("Token："+(String) JSONUtil.getStringFromJSONObject(resultMap.get("resultJson"), "access_token"));
			accessToken = (String) JSONUtil.getStringFromJSONObject(resultMap.get("resultJson"), "access_token");
			openId = (String) JSONUtil.getStringFromJSONObject(resultMap.get("resultJson"), "openid");
		}else {
			//如果有errmsg说明出错了
			log.info((String) JSONUtil.getStringFromJSONObject(resultMap.get("resultJson"), "errmsg"));
			errmsg  = (String) JSONUtil.getStringFromJSONObject(resultMap.get("resultJson"), "errmsg");
			modelMap.addAttribute("errmsg", errmsg);
			return "showcode";
		}
		log.info("拉取用户信息");
		//拉取用户的个人信息
		String url = "https://api.weixin.qq.com/sns/userinfo";
		Map<String, String> userInfoMap = new HashMap<String, String>();
		userInfoMap.put("access_token", accessToken);
		userInfoMap.put("openid", openId);
		userInfoMap.put("lang", "zh_CN");
		NetWorkCenter.get(url, userInfoMap, new NetWorkCenter.ResponseCallback() {
			
			@Override
			public void onResponse(int resultCode, String resultJson) {
				// TODO Auto-generated method stub
				if (resultCode == 200) {
					log.info(resultJson);
					resultMap.put("userInfo", resultJson);
					
				}
			}
		});
		
		if (resultMap.get("userInfo") != null) {
			log.info("转换成User对象");
			User user = new User();
			String userJson = resultMap.get("userInfo");
			user.setOpenid((String) JSONUtil.getStringFromJSONObject(userJson, "openid"));
			user.setNickname((String) JSONUtil.getStringFromJSONObject(userJson, "nickname"));
			user.setLanguage((String) JSONUtil.getStringFromJSONObject(userJson, "language"));
			user.setSex( Integer.parseInt((String) JSONUtil.getStringFromJSONObject(userJson, "sex")));
			user.setCity((String) JSONUtil.getStringFromJSONObject(userJson, "city"));
			user.setProvince((String) JSONUtil.getStringFromJSONObject(userJson, "province"));
			user.setCountry((String) JSONUtil.getStringFromJSONObject(userJson, "country"));
			user.setHeadimgurl((String) JSONUtil.getStringFromJSONObject(userJson, "headimgurl"));
			user.setPrivilege((String) JSONUtil.getStringFromJSONObject(userJson, "privilege"));
			modelMap.addAttribute("user",user);
		}
		modelMap.addAttribute("msg", message);
		return "showcode";
	}
	
	
}
